#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <chrono>

// Boost.Asio 定时器基础示例
// 演示异步定时器的使用

void print_handler(const boost::system::error_code& ec) {
    if (!ec) {
        std::cout << "Timer expired! Hello from async timer!" << std::endl;
    } else {
        std::cout << "Timer error: " << ec.message() << std::endl;
    }
}

class TimerDemo {
private:
    boost::asio::io_context& io_;
    boost::asio::steady_timer timer_;
    int count_;

public:
    TimerDemo(boost::asio::io_context& io)
        : io_(io), timer_(io, std::chrono::seconds(1)), count_(0) {
        timer_.async_wait([this](const boost::system::error_code& ec) {
            this->handle_timeout(ec);
        });
    }

    void handle_timeout(const boost::system::error_code& ec) {
        if (!ec) {
            std::cout << "Count: " << count_ << std::endl;
            ++count_;

            if (count_ < 5) {
                timer_.expires_after(std::chrono::seconds(1));
                timer_.async_wait([this](const boost::system::error_code& ec) {
                    this->handle_timeout(ec);
                });
            }
        }
    }
};

int main() {
    try {
        std::cout << "=== Boost.Asio Timer Examples ===" << std::endl;

        boost::asio::io_context io;

        // 示例1: 简单的同步定时器
        std::cout << "\n1. Synchronous timer example:" << std::endl;
        boost::asio::steady_timer sync_timer(io, std::chrono::seconds(2));
        std::cout << "Waiting for 2 seconds..." << std::endl;
        sync_timer.wait();
        std::cout << "2 seconds have passed!" << std::endl;

        // 示例2: 异步定时器
        std::cout << "\n2. Asynchronous timer example:" << std::endl;
        boost::asio::steady_timer async_timer(io, std::chrono::seconds(1));
        async_timer.async_wait(print_handler);

        // 示例3: 重复定时器
        std::cout << "\n3. Repeating timer example:" << std::endl;
        TimerDemo demo(io);

        // 运行事件循环
        io.run();

        std::cout << "\nAll timers completed!" << std::endl;

    } catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
